<?php

class DispatchReturnsController extends AppController {

    var $name = 'DispatchReturns';
    var $viewPath = 'its/returns/dispatch_returns';
    var $pageTitle = 'Dispatch Return Information';
    var $uses = array('DRH', 'DR', 'Dispatch', 'DispatchStatus', 'CustStockIn', 'Product', 'ProductSerial', 'RunningNo', 'Location', 'UserCoH');
    var $paginate = array(
        'DRH' => array(
            'order' => 'DRH.id DESC'
        )
    );

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'its_returns');
        $this->set('tabMenu', 'tabmenus/its/returns');
    }

    function display() {
        parent::display('DRH');
        $this->paginate['DRH']['contain'] = array('Customer', 'Site', 'Dispatch', 'Warehouse');

        $this->_checkCustomerOnHand('DRH');

        $op = array(
            'customer_id' => '=',
        );
        
        $this->_paging('DRH', $op);
    }

    function save() {
        $is_success = true;
        $drh_id = null;
        if ($this->data['mode'] == 'add') {
            $is_success = $this->_save_return();
        } else { // mode == 'edit'
            $this->DRH->id = $this->data['DRH']['id'];
            $is_success = $this->DRH->saveField('remark', $this->data['DRH']['remark']);
            $is_success &= $this->DRH->saveField('collector_id', $this->Auth->user('id'));
        }

        if ($is_success) {
            $drh_id = $this->DRH->id;
            $this->Session->setFlash("Save succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Save fail !", 'flash/fail');
        }

        $this->data['DR'] = null;
        $this->setAction('view', $drh_id);
    }

    function _save_return() {
        $drh_id = null;
        $is_success = true;
        // ตรวจสอบว่ามีรายการเข้ามาหรือไม่
        if (!empty($this->data['DRH']['dispatch_id'])) {
            $this->DRH->query("BEGIN");
            ;

            // กำหนดข้อมูล Dispatch Return Head
            // Generate return no
            $year = $this->Utility->getThaiYear();
            $runno = $this->RunningNo->getNextStockNo(RunningNo::DISPATCH_RETURN_TYPE, $year);
            $this->data['DRH']['return_no'] = RunningNo::DISPATCH_RETURN_TYPE . $year . $runno;
            $this->data['DRH']['collector_id'] = $this->Auth->user('id');
            $this->ProductSerial->validate['location_id'] = array('rule' => 'notEmpty', 'message' => 'Please select a product serial location.');
            if ($this->DRH->saveAll($this->data, array('validate' => 'first', 'atomic' => false)) == true) {    // ถ้าไม่ใช่จะ return array error field
                // update Dispatch ว่ามีการ Return
                $this->Dispatch->id = $this->data['DRH']['dispatch_id'];
                $this->Dispatch->saveField('is_dispatch_return', true);

                // ถ้าเป็น On Dispatch เปลี่ยนเป็น Cancel
                if ($this->data['dispatch_status_id'] == DispatchStatus::ON_DISPATCH_STATUS) {
                    $this->Dispatch->saveField('dispatch_status_id', DispatchStatus::CANCEL_STATUS);
                }

                $drh_id = $this->DRH->id;
                foreach ($this->data['DR'] as $dR) {
                    // Update Cust Product Site current stock
                    $return_qty = $dR['return_qty'];
                    $this->Product->id = $dR['product_id'];
                    $current_stock = $this->Product->field('current_stock');
                    $is_success &= $this->Product->saveField('current_stock', $current_stock + $return_qty);

                    // Update CustStockIn Dispatch Status
                    $this->CustStockIn->id = $dR['cust_stock_in_id'];
                    $dispatch_status_id = $this->CustStockIn->field('dispatch_status_id');
                    if ($dispatch_status_id == DispatchStatus::ON_DISPATCH_STATUS) {
                        $this->CustStockIn->saveField('dispatch_status_id', DispatchStatus::CANCEL_STATUS);
                    }

                    // ดึงรายการ dispatch_return
                    $this->DR->contain();
                    $_dr = $this->DR->find('first', array(
                                'conditions' => array(
                                    'DR.product_id' => $dR['product_id'],
                                    'dispatch_return_head_id' => $drh_id
                                )
                                    )
                    );

                    // คัดลอก ProductSerial เดิม มาใส่อันใหม่
                    for ($i = 0; $i < $return_qty; ++$i) {
                        $this->ProductSerial->contain();
                        $ps = $this->ProductSerial->findById($dR['ProductSerial'][$i]['id']);

                        $data = array();
                        $data['ProductSerial']['id'] = null;
                        $data['ProductSerial']['product_id'] = $_dr['DR']['product_id'];
                        $data['ProductSerial']['serial_no'] = $ps['ProductSerial']['serial_no'];
                        $data['ProductSerial']['other_information'] = $ps['ProductSerial']['other_information'];
                        $data['ProductSerial']['cost'] = $ps['ProductSerial']['cost'];
                        $data['ProductSerial']['price'] = $ps['ProductSerial']['price'];
                        $data['ProductSerial']['location_id'] = $dR['ProductSerial'][$i]['location_id'];
                        $data['ProductSerial']['its_stock_in_type'] = DR::ITS_STOCK_IN_TYPE;
                        $data['ProductSerial']['its_stock_in_id'] = $_dr['DR']['id'];
                        $data['ProductSerial']['stock_out_priority'] = $ps['ProductSerial']['stock_out_priority'];
                        $data['ProductSerial']['is_active_flag'] = true;

                        // update ProductSerial เดิมว่าใช้งานไม่ได้
                        $this->ProductSerial->id = $ps['ProductSerial']['id'];
                        $this->ProductSerial->saveField('is_active_flag', false);

                        // บันทึก ProductSerial อันใหม่
                        $this->ProductSerial->create();
                        $is_success &= $this->ProductSerial->save($data);
//                        debug($this->ProductSerial->findById($this->ProductSerial->id));
                    }
                }
            } else {
                $is_success = false;
            }
            if ($is_success) {
                $this->DRH->query("COMMIT");
                ;
            } else {
                $this->passedArgs['dispatch_id'] = $this->data['DRH']['dispatch_id'];
                $this->DRH->query("ROLLBACK");
            }
        } else {
            $this->data = null;
            return false;
        }
        return $is_success;
    }

    function view($id = null) {
        // edit หรือมาจากหน้า dispatch
        if ($id != null) {
            $this->DRH->contain(array('Customer', 'Site', 'Dispatch', 'Warehouse', 'DR' => array('Product' => array('Unit'))));

            if (isset($this->passedArgs['return_dispatch_id'])) {
                $this->data = $this->DRH->findByDispatchId($this->passedArgs['return_dispatch_id']);
            } else {
                $this->data = $this->DRH->findById($id);
            }

            $this->_neighbors($id, $this->DRH, array('fields' => array('id')));
            $this->set('mode', 'edit');
        } else {
            // ดึงรายการ Dispatch ที่ Partial หรือ On Dispatch ที่ยังไม่ได้ทำการ Return
            $this->set('dispatches', $this->Dispatch->find('list', array(
                        'conditions' => array(
                            'dispatch_status_id' => array(
                                DispatchStatus::ON_DISPATCH_STATUS,
                                DispatchStatus::PARTIAL_CONSIGNED_STATUS
                            ),
                            'is_dispatch_return' => null
                        )
                            )
                    )
            );

            if (isset($this->passedArgs['dispatch_id'])) {
                $this->CustStockIn->bindModel(array('hasMany' => array(
                        'ProductSerial' => array(
                            'foreignKey' => 'its_stock_out_id',
                            'conditions' => array(
                                'its_stock_out_type' => CustStockIn::ITS_STOCK_OUT_TYPE,
                                'cust_stock_in_id' => null, // เฉพาะ ที่ไม่ได้ stock in
                                'is_active_flag' => true      // เฉพาะ ที่ยังไม่ได้ return
                            )
                        )
                    )
                        )
                );
                $this->Dispatch->contain(array('Customer', 'Site', 'Warehouse',
                    'CustStockIn' => array(
                        'Product' => array('Unit'), 'ProductSerial',
                        'conditions' => array(
                            'CustStockIn.dispatch_status_id' => array(
                                DispatchStatus::ON_DISPATCH_STATUS,
                                DispatchStatus::CANCEL_STATUS,
                                DispatchStatus::PARTIAL_CONSIGNED_STATUS
                            )
                        )
                    )
                        )
                );
                $this->data = $this->Dispatch->findById($this->passedArgs['dispatch_id']);
                $this->set('locations', $this->Location->find('list', array('conditions' => array('warehouse_id' => $this->data['Dispatch']['warehouse_id']))));
            }

            $this->set('mode', 'add');
            $this->set('return_by', $this->Auth->user('name'));
            $this->set('today', date("d/m/Y"));
        }
    }

    function print_view($id) {
        $this->layout = 'print';
        $this->data = $this->DRH->findForPrintById($id);
    }

}

?>